<template>
  <div class="dustbinbox">
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      ref="scrollTable"
      height="100%"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="fileName"
        align="left"
        width="400"
      >
        <template slot="header">
          {{ headerTitle }}
          <span v-if="multipleSelection.length!=0" class="btns">
          <el-button type="primary" size="mini" @click="restoreFile()">还原</el-button>
          <el-button size="mini" @click="deleteFile()">删除</el-button>
        </span>

        </template>
        <template slot-scope="scope">
          <div class="fileName">
            <img
              :src="FileImage[scope.row.extendName]? FileImage[scope.row.extendName]:require('@/assets/image_library/netmini.png')"
            />
            <div>{{ scope.row.fileName + `${scope.row.extendName ? '.' + scope.row.extendName : ''}` }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="fileSize"
        label="大小"
        align="center"
      >
        <template slot-scope="scope">
          {{ convertBytes(scope.row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="delTime"
        label="删除时间"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">{{ scope.row.delTime | fifterTime }}</template>
      </el-table-column>
      <el-table-column
        prop="Effective"
        label="有效时间"
        align="center"
      >
        <template slot-scope="scope">
          <div :class="(scope.row.validDay*1)>7?'':'redtext'">
            {{ scope.row.validDay === 0 ? '<1' : scope.row.validDay }}天
          </div>

        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" icon="el-icon-refresh-left" type="text" @click="restoreFile(scope.row.recoveryId)"/>
          <el-button size="mini" icon="el-icon-delete" type="text" @click="deleteFile(scope.row.recoveryId)"/>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { deleteDustbinList, resetDustbinItem } from '@/api/library_index'
import { convertBytes } from '@/views/library_homePage/utils/files'

export default {
  name: 'dustbin',
  props: {
    tableData: {
      required: true,
      type: Array
    }
  },
  // 过滤时间
  filters: {
    fifterTime(value) {
      if (!value) return ''
      const time = new Date(value)
      const newDate = new Date(
        time.getFullYear(),
        time.getMonth(),
        time.getDate(), // 减一天
        time.getHours() + 8,
        time.getMinutes(),
        time.getSeconds()
      )
      return newDate.toISOString().replace('T', ' ').slice(0, 19).replace('T', ' ')
    }

  },
  data() {
    return {
      multipleSelection: [],
      headerTitle: '文件名',
      FileImage: {
        'pdf': require('@/assets/image_library/pdfmini.png'),
        'docx': require('@/assets/image_library/wordmini.png'),
        'dov': require('@/assets/image_library/wordmini.png'),
        'xls': require('@/assets/image_library/excelmini.png'),
        'xlsx': require('@/assets/image_library/excelmini.png'),
        'ppt': require('@/assets/image_library/pptmini.png'),
        'pptx': require('@/assets/image_library/pptmini.png'),
        'txt': require('@/assets/image_library/textmini.png'),
        'zip': require('@/assets/image_library/zipmini.png'),
        'rar': require('@/assets/image_library/zipmini.png'),
        'mp3': require('@/assets/image_library/musicmini.png'),
        null: require('@/assets/image_library/dirsmall.png'),
        'mp4': require('@/assets/image_library/videomini.png')
      },
      convertBytes: function(num) {
        return convertBytes(num)
      },
      timer: null
    }
  },
  mounted() {
    this.loadMoreData = this.debounce(this.loadMoreData, 500)
    /**
     * @description:添加分页加载滚动事件
     * @return {*}
     */
    let table = this.$refs.scrollTable.bodyWrapper
    table.addEventListener('scroll', (e) => {
      const { scrollTop, clientHeight, scrollHeight } = e.target
      // 检查是否滚动到底部
      if (scrollHeight - scrollTop <= clientHeight) {
        this.loadMoreData()
      }
    })
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
      if (this.multipleSelection.length > 0) {
        this.headerTitle = `已选中${this.multipleSelection.length}个文件/文件夹`
      } else {
        this.headerTitle = '文件名'
      }
    },
    restoreFile(id) {
      let arr = []
      if (id) {
        arr.push(id)
      } else {
        arr = this.multipleSelection.map(item => item.recoveryId)
      }
      this.$confirm(`确定还原所选文件？`, '还原确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        let res = await resetDustbinItem({ recoveryIdList: arr })
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '还原成功!'
          })
          // TODO:重新获取数据
          this.$parent.getdustbin()
        }

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消还原'
        })
      })
    },
    deleteFile(id) {
      let arr = []
      if (id) {
        arr.push(id)
      } else {
        arr = this.multipleSelection.map(item => item.recoveryId)
      }
      this.$confirm(`删除后无法恢复，确认彻底删除所选文件吗？`, '彻底删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        let res = await deleteDustbinList({ recoveryIdList: arr })
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // TODO:重新获取数据
          this.$parent.getdustbin()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    debounce(fn, delay, immediate = false) {
      let timer
      return function(...args) {
        const context = this
        if (immediate && !timer) {
          fn.apply(context, args)
        }
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          if (!immediate) {
            fn.apply(context, args)
          }
          timer = null
        }, delay)
      }
    },
    loadMoreData() {
      this.$emit('lookMore')
    }
  }
}
</script>
<style scoped lang="scss">
.redtext {
  color: red;
}

.dustbinbox {
  height: 100%;
  overflow-y: auto;
}

.btns {
  margin-left: 15px;
}

.fileName {
  display: flex;
  align-items: center;

  img {
    width: 15px;
    height: 16px;
    margin-right: 10px;
  }
}
</style>
